package com.wsjc.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.wsjc.common.core.constants.CommonConst;
import com.wsjc.common.core.utils.RandomUtils;
import com.wsjc.common.rabbitmq.impl.RmqProducerUtils;
import com.wsjc.manager.entity.WjDataLog;
import com.wsjc.manager.entity.WjSterilization;
import com.wsjc.manager.service.routine.datalog.WjDataLogService;

@RestController
@RequestMapping(value = "/pc/")
public class PcDataController {

	   
	private Logger logger = LoggerFactory.getLogger(PcDataController.class);
	
	
	@Autowired
	private RmqProducerUtils rmqProducerUtils ; 
	
	@Autowired
	private WjDataLogService wjDataLogService ;

	/**
	 * 上传二进制数据包
	 * @param PartID
	 * @param Key
	 * @param FileName
	 * @param PDFFileName
	 * @param session
	 * @param error_info
	 * @return
	 */
	@RequestMapping(value = "upData", method = RequestMethod.GET)
	public String upData(String localDtbPath, String localPdfPath, String ossDtbPath, String ossPdfPath, MultipartFile FileName, MultipartFile PDFFileName,
			HttpSession session , String error_info) {
		
//		int total = 1 ;
		int total = 100 ;
		
		
		logger.info("定时任务启动 : 灭菌数据上传到 DB .....");
		// 启示时间
		long starTime = System.currentTimeMillis();

		// 再读取对象
		File file = new File(CommonConst.LOCAL_FILE_PATH_STERILIZATIONS + "\\sterilizations.txt");
		FileInputStream fis;
		try {
			fis = new FileInputStream(file);
			ObjectInputStream objIP = new ObjectInputStream(fis);
			// 读取对象数据，需要将对象流强制转换为 要写入对象的类型
			List<WjSterilization> sterilizations = (List<WjSterilization>)objIP.readObject();

			logger.info("SYN-STERILIZATION-DATA|data size --> " + sterilizations.size());
			
			total = sterilizations.size();
			int i = 0 ;
			for(WjSterilization wjSterilization : sterilizations){
				
				i++;
				if(i > 1){
					break;
				}
				WjDataLog wjDataLog = new WjDataLog();
				wjDataLog.setDataId(wjSterilization.getId());
				/** 日志id 六位areaId + 13位时间戳 + 5位随机数**/
				StringBuffer buf = new StringBuffer();
				String id = wjDataLog.getDataId().substring(5, 11) ;
				buf.append(id).append(System.currentTimeMillis()).append(RandomUtils.randomInt(5));
				wjDataLog.setId(buf.toString());
//				wjDataLog.setId(System.currentTimeMillis()+"");
				wjDataLog.setDataType("00S");
				wjDataLog.setDataStatus(CommonConst.DATA_STATUS_CREATE);
				wjDataLog.setMapStatus(CommonConst.DATA_STATUS_CREATE);
				wjDataLog.setStatisticsStatus(CommonConst.DATA_STATUS_CREATE);
				wjDataLog.setPushStatus(CommonConst.DATA_STATUS_CREATE);
				
				//vo
				wjDataLog.setHospitalId(wjSterilization.getHospitalId());
				wjDataLog.setDetectionResult(wjSterilization.getDetectionResult());
				wjDataLogService.saveData(wjDataLog);
				
				
				String message = JSONObject.toJSONString(wjDataLog);
				rmqProducerUtils.sendDefaultData(message, wjDataLog.getId());
			 	
			}
			
			System.out.println("好使");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		return "sucssesful" ;
		
		
	}

							 
	/**************************************************** 解析数据包 *******************************************/
/*
	*//**
	 * 3.1 数据上传 请求方式 ：POST 参数 ：partID : 单位ID , Key 软件秘钥 , FileName 二进制数据包（六种）,
	 * PDFFileName pdf文件
	 * 
	 * @return 0 不成功 , 1 成功
	 *//*
	@RequestMapping(value = "upData", method = RequestMethod.POST)
	public Map<String, Object> upData(String PartID, String Key, MultipartFile FileName, MultipartFile PDFFileName,
			HttpSession session) {
		log.info("PC接口 :3.1 " + DateUtil.getTime());
		long star_Time = System.currentTimeMillis();
		// 验证秘钥
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		String city_id = "";
		String hospital_id = "";
		String up_user = "";
		try {
			up_user = PartID.substring(6, 8).toString();
			city_id = PartID.substring(0, 6).toString();
			hospital_id = PartID.substring(6).toString();
		} catch (Exception e) {
			return MapModel.getMapModel("0", "", "用户名异常");
		}
		paramsMap.put("hospital_id", hospital_id);
		paramsMap.put("t_hospital", Constants.T_HOSPITAL + city_id);
		Hospital hospital = null;
		System.out.println(paramsMap);

		try {
			hospital = pcService.findHospitalByID(paramsMap);
		} catch (Exception e) {
			log.info("捕获异常：" + DateUtil.getTime() + " " + e.getMessage());
			return MapModel.getMapModel("0", "", "正在建设中，请耐心等待");
		}
		if (null == hospital) {
			return MapModel.getMapModel("0", "", "单位不存在");
		}
		if (!hospital.getHospital_key().equals(Key)) {
			return MapModel.getMapModel("0", "", "秘钥不正确");
		}
		// 验证文件格式
		boolean falg = UploadUtil.YzPdfType(PDFFileName);
		if (!falg) {
			return MapModel.getMapModel("0", "", "pdf文件格式不对");
		}
		falg = UploadUtil.YzDtbType(FileName);
		if (!falg) {
			return MapModel.getMapModel("0", "", "dtb文件格式不对");
		}

		// 开始解析二进制数据包
		long end_Time = System.currentTimeMillis();
		long Time = end_Time - star_Time;
		String ID = UUIDUtil.getRandom32EndTimePK();
		Map<String, Object> Map;
		String testID = "";
		try {
			Map = ParseData.analysis(FileName.getInputStream());
			String type = (String) Map.get("type");
			System.out.println(" 二进制 的 类型 是 ：" + type);
			if (type.equals("mj")) { // 灭菌效果
				Sterilization mj = (Sterilization) Map.get("mj");
				testID = "00s" + city_id + ID;
				mj.setS_id(testID);
				
				mj.setTable_testName(Constants.T_STERILIZATION + city_id);
				mj.setHospital_id(hospital_id);
				mj.setUp_user(up_user);
				System.out.println("  解析出来的 “灭菌效果” 的数据是 ：" + mj);

				// 效验监测数据是否存在
				Map<String, Object> mj_map = new HashMap<String, Object>();
				mj_map.put("test_tableName", Constants.T_STERILIZATION + city_id);
				mj_map.put("recorder_id", mj.getRecorder_id());
				mj_map.put("hospital_id", hospital_id);
				mj_map.put("test_time", mj.getTest_time());
				int count = pcService.checkTestData(mj_map);
				if (count != 0) {
					return MapModel.getMapModel("0", "", "该监测数据已存在");
				}
				if (mj.getTest_result().equals("不合格")) {
					mj.setTest_result("2");
					
					//查找起点 ,说明 ： 查不合格
					paramsMap.put("device_number", mj.getDevice_number()) ;   // 设备编号
					paramsMap.put("test_tableName", Constants.T_STERILIZATION + city_id ) ;
					Hostpital_Device_result hdr = helpService.selectHospitalNewTestResult(paramsMap) ;
					//最新的一条不合格
					if(hdr != null){
						if(hdr.getTest_result().equals("2") ){
							if(hdr.getStart_node()==null){
								mj.setStart_node(testID);    // 最新的一条就是 不合格的那么存入自己的id 作为起始点
							}else{
								mj.setStart_node(hdr.getStart_node());    // 存入起始点的id
							}
						}else{
							//最新的一条是合格的
							mj.setStart_node(hdr.getS_id());  
						}
					}else{
						mj.setStart_node(testID);  
					}
					tools(hospital_id, city_id, "灭菌效果检测", mj.getTest_time() , testID , mj.getSmsInfo() );
				} else {
					mj.setTest_result("1");
				}
				pcService.addMJ_DTB(mj);
			} else if (type.equals("mjsb")) { // 灭菌设备
				Sterilization_device mjsb = (Sterilization_device) Map.get("mjsb");
				testID = "0sd" + city_id + ID;
				mjsb.setSd_id(testID);
				if (mjsb.getTest_result().equals("不合格")) {
					mjsb.setTest_result("2");
					tools(hospital_id, city_id, "灭菌设备检测", mjsb.getTest_time() , testID , "" );
				} else {
					mjsb.setTest_result("1");
				}
				mjsb.setTable_testName(Constants.T_STERILIZATION_DEVICE + city_id);
				mjsb.setHospital_id(hospital_id);
				mjsb.setUp_user(up_user);

				// 效验监测数据是否存在
				
				 * Map<String , Object > mjsb_map = new HashMap<String,
				 * Object>() ; mjsb_map.put("test_tableName",
				 * Constants.T_STERILIZATION_DEVICE + city_id ) ;
				 * mjsb_map.put("device_number", mjsb.getDevice_number() ) ;
				 * mjsb_map.put("test_time", mjsb.getTest_time() ) ; int count =
				 * pcService.checkTestData(mjsb_map) ; if(count != 0 ){
				 * //System.out.println("  灭菌检测数据已存在"); // return
				 * MapModel.getMapModel("0", "", "该监测数据已存在"); return
				 * MapModel.getMapModel("1", "上传成功", ""); }
				 

				pcService.addMD_DTB(mjsb);
			} else if (type.equals("xd")) { // 消毒效果
				Disinfected d = (Disinfected) Map.get("xd");
				testID = "00d" + city_id + ID;
				d.setD_id(testID);
				if (d.getTest_result().equals("不合格")) {
					d.setTest_result("2");
					tools(hospital_id, city_id, "消毒效果检测", d.getTest_time() , testID , "");
				} else {
					d.setTest_result("1");
				}
				d.setTable_testName(Constants.T_DISINFECTED + city_id);
				d.setHospital_id(hospital_id);
				d.setUp_user(up_user);

				// 效验监测数据是否存在
				
				 * Map<String , Object > xd_map = new HashMap<String, Object>()
				 * ; xd_map.put("test_tableName", Constants.T_DISINFECTED +
				 * city_id ) ; xd_map.put("device_number", d.getDevice_number()
				 * ) ; xd_map.put("test_time", d.getTest_time() ) ; int count =
				 * pcService.checkTestData(xd_map) ; if(count != 0 ){
				 * //System.out.println("  灭菌检测数据已存在"); // return
				 * MapModel.getMapModel("0", "", "该监测数据已存在"); return
				 * MapModel.getMapModel("1", "上传成功", ""); }
				 

				pcService.addD_DTB(d);
			} else if (type.equals("atp")) { // ATP测试
				Atp_test atp = (Atp_test) Map.get("atp");
				testID = "atp" + city_id + ID;
				atp.setAtp_id(testID);
				atp.setTable_testName(Constants.T_ATP_TEST + city_id);
				atp.setHospital_id(hospital_id);
				Collections.sort(atp.test_messages);
				Collections.reverse(atp.test_messages);
				if (atp.test_messages.get(0).getTest_result().equals("不合格")) {
					atp.setTest_result("2");
					tools(hospital_id, city_id, "atp测试", atp.getTest_time() , testID , "");
				} else {
					atp.setTest_result("1");
				}
				atp.setTest_time(atp.test_messages.get(0).getTest_time());
				atp.setUp_user(up_user);

				// 效验监测数据是否存在
				
				 * Map<String , Object > atp_map = new HashMap<String, Object>()
				 * ; atp_map.put("test_tableName", Constants.T_ATP_TEST +
				 * city_id ) ; atp_map.put("device_number",
				 * atp.getDevice_number() ) ; atp_map.put("test_time",
				 * atp.getTest_time() ) ; int count =
				 * pcService.checkTestData(atp_map) ; if(count != 0 ){
				 * //System.out.println("  灭菌检测数据已存在"); // return
				 * MapModel.getMapModel("0", "", "该监测数据已存在"); return
				 * MapModel.getMapModel("1", "上传成功", ""); }
				 

				pcService.addATP_DTB(atp);
				for (AtpBaseData abd : atp.test_messages) {
					if (abd.getTest_result().equals("不合格")) {
						abd.setTest_result("2");
					} else {
						abd.setTest_result("1");
					}
					abd.setAtp_id(testID);
					abd.setTable_testName(Constants.T_ATP_TEST_SON + city_id);
					pcService.addATP_SON_DTB(abd);
				}
			} else if (type.equals("bd")) { // BD测试
				Bd_test bd = (Bd_test) Map.get("bd");
				testID = "0bd" + city_id + ID;
				bd.setBd_id(testID);
				if (bd.getTest_result().equals("不合格")) {
					bd.setTest_result("2");
					tools(hospital_id, city_id, "bd测试", bd.getTest_time() , testID ,"");
				} else {
					bd.setTest_result("1");
				}
				bd.setTable_testName(Constants.T_BD_TEST + city_id);
				bd.setHospital_id(hospital_id);
				bd.setUp_user(up_user);

				// 效验监测数据是否存在
				
				 * Map<String , Object > bd_map = new HashMap<String, Object>()
				 * ; bd_map.put("test_tableName", bd.getTable_testName() ) ;
				 * bd_map.put("device_number", bd.getDevice_number() ) ;
				 * bd_map.put("test_time", bd.getTest_time() ) ; int count =
				 * pcService.checkTestData(bd_map) ; if(count != 0 ){
				 * //System.out.println("  灭菌检测数据已存在"); // return
				 * MapModel.getMapModel("0", "", "该监测数据已存在"); return
				 * MapModel.getMapModel("1", "上传成功", ""); }
				 

				pcService.addBD_DTB(bd);
			} else if (type.equals("uv")) { // 紫外检测
				Uv_test uv = (Uv_test) Map.get("uv");
				testID = "0uv" + city_id + ID;
				uv.setUv_id(testID);

				if (uv.getTest_result().equals("不合格")) {
					uv.setTest_result("2");
					tools(hospital_id, city_id, "紫外检测", uv.getTest_time() , testID ,"");
				} else {
					uv.setTest_result("1");
				}
				uv.setTable_testName(Constants.T_UV + city_id);
				uv.setHospital_id(hospital_id);
				uv.setUp_user(up_user);
				// 效验监测数据是否存在
				Map<String, Object> uv_map = new HashMap<String, Object>();
				uv_map.put("test_tableName", uv.getTable_testName());
				uv_map.put("device_number", uv.getDevice_number());
				uv_map.put("test_time", uv.getTest_time());
				System.out.println(" 效验 该条数据是否存在  参数  ：" + uv_map);

				int count = pcService.checkTestData(uv_map);
				if (count != 0) {
					System.out.println("紫外检测数据已存在");
					// return MapModel.getMapModel("0", "", "该监测数据已存在");
					return MapModel.getMapModel("1", testID , "");
				}
				pcService.addUV_DTB(uv);
			} else {
				return MapModel.getMapModel("0", "", "数据检测类别不匹配");
			}

			System.out.println("解析二进制数据包    一共耗时 ：" + (double) Time / 1000 + " 秒");
			*//********* 上传OSS ************//*
			String filePathName = Constants.UP_OSS_FILEPATH_PDF + testID + ".pdf";
			// String filePathName = "dev/"+ testID + ".pdf";
			OSSFile.openBucketAndUpFile(PDFFileName.getInputStream(), filePathName);

			// filePathName = "dev/" + testID + ".dtb";
			filePathName = Constants.UP_OSS_FILEPATH_DTB + testID + ".dtb";
			OSSFile.openBucketAndUpFile(FileName.getInputStream(), filePathName);

		} catch (IOException e) {
			*//********** 删除图片 ************//*
			log.info("捕获异常：" + DateUtil.getTime() + " " + e.getMessage());
			return MapModel.getMapModel("0", "", "解析文件出错");
		}

		end_Time = System.currentTimeMillis();
		Time = end_Time - star_Time;
		System.out.println("pc接口3.1执行完毕  ：" + (double) Time / 1000 + " 秒 ， testId :" + ID);
		return MapModel.getMapModel("1", testID , "");
	}
	
	

	// pdf
	@RequestMapping(value = "downPDF", method = RequestMethod.GET)
	public Map<String, Object> downPDF(String PartID, String Key, String TestID, HttpSession session,
			HttpServletResponse response) {
		log.info("PC接口 :pdf下载 " + DateUtil.getTime());

		// 处理空格
		PartID = PartID.replace(" ", "");
		// 处理PartID 大小写
		try {
			PartID = HelpUtil.TreateHospitalID(PartID);
			// 验证秘钥
			Map<String, Object> paramsMap = new HashMap<String, Object>();
			String city_id = PartID.substring(0, 6).toString();
			String hospital_id = PartID.substring(6).toString();
			paramsMap.put("hospital_id", hospital_id);
			paramsMap.put("t_hospital", Constants.T_HOSPITAL + city_id);
			Hospital hospital = null;
			try {
				hospital = pcService.findHospitalByID(paramsMap);
			} catch (Exception e) {
				log.info("捕获异常：" + DateUtil.getTime() + " " + e.getMessage());
				return MapModel.getMapModel("0", "", "正在建设中，请耐心等待！");
			}
			if (null == hospital) {
				return MapModel.getMapModel("0", "", "单位不存在");
			}
			if (!hospital.getHospital_key().equals(Key)) {
				return MapModel.getMapModel("0", "", "秘钥不正确");
			}
			if (null != hospital.getUse_expiry_date()) {
				if (new Date().getTime() > hospital.getUse_expiry_date().getTime()) {
					return MapModel.getMapModel("1", "", "有效期过期");
				}
			}
			// 解析 测试类别
			String dtbType = TestID.substring(0, 3).toString();
			String test_id = TestID;
			paramsMap.put("TestId", test_id);
			int num = 0;
			if (dtbType.equals("00s")) { // 灭菌效果
				paramsMap.put("test_tableName", Constants.T_STERILIZATION + city_id);
				paramsMap.put("id", "s_id");
			} else if (dtbType.equals("0sd")) { // 灭菌设备
				paramsMap.put("test_tableName", Constants.T_STERILIZATION_DEVICE + city_id);
				paramsMap.put("id", "sd_id");
			} else if (dtbType.equals("00d")) { // 消毒
				paramsMap.put("test_tableName", Constants.T_DISINFECTED + city_id);
				paramsMap.put("id", "d_id");
			} else if (dtbType.equals("0uv")) { // 紫外
				paramsMap.put("test_tableName", Constants.T_UV + city_id);
				paramsMap.put("id", "uv_id");
			} else if (dtbType.equals("0db")) { // DB测试
				paramsMap.put("test_tableName", Constants.T_BD_TEST + city_id);
				paramsMap.put("id", "bd_id");
			} else if (dtbType.equals("atp")) { // ATP测试
				paramsMap.put("test_tableName", Constants.T_ATP_TEST + city_id);
				paramsMap.put("id", "atp_id");
			} else {
			}
			num = pcService.CheckDtbNumByID(paramsMap);
			if (num == 0) {
				return MapModel.getMapModel("2", "", "测试号不符合权限");
			}
			String ossPath = Constants.UP_OSS_FILEPATH_PDF + test_id + ".pdf";
			String pdfFilePath = session.getServletContext().getRealPath(Constants.UPLOAD_PDF_PATH) + "\\" + test_id
					+ ".pdf";
			*//*************** Oss 下载文件 *****************//*
			OSSFile.DownFile(ossPath, pdfFilePath);
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName=" + test_id + ".pdf");
			byte[] pdf_type = null;
			try {
				InputStream inputStream = new FileInputStream(pdfFilePath);
				OutputStream os = response.getOutputStream();
				pdf_type = new byte[1024 * 2];
				int length;
				while ((length = inputStream.read(pdf_type)) > 0) {
					os.write(pdf_type, 0, length);
				}
				inputStream.close();
			} catch (FileNotFoundException e) {
				UploadUtil.delFile(pdfFilePath);
				log.info("捕获异常：" + DateUtil.getTime() + " " + e.getMessage());
				return MapModel.getMapModel("0", "", "OSS下载文件出错，稍后再试！");
			} catch (IOException e) {
				UploadUtil.delFile(pdfFilePath);
				log.info("捕获异常：" + DateUtil.getTime() + " " + e.getMessage());
				return MapModel.getMapModel("0", "", "OSS下载文件出错，稍后再试！");
			}
			boolean fal = UploadUtil.delFile(pdfFilePath);
			if (fal) {
				System.out.println("删除成功.........");
			} else {
				System.out.println("删除失败..................");
			}
		} catch (Exception e1) {
			return MapModel.getMapModel("0", "", "用户名异常");
		}
		return null;

	}

	*//**
	 * 下载账单
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 *//*
	@RequestMapping("downChnBill")
	public ResponseEntity<byte[]> downChnBill(HttpServletRequest request) {
		String startDay = request.getParameter("startDate");
		if(startDay == null){
			throw new BizException("起始日期不能为空");
		}
		String endDay = request.getParameter("endDate");
		if(endDay == null){
			throw new BizException("终止日期不能为空");
		}
		String startDate = startDay.replace("-", "");
		String endDate = endDay.replace("-", "");
		String chnId = request.getParameter("chnid");
		String chnName = request.getParameter("chnName");
		String payType = request.getParameter("payType");

		StringBuilder sbContent = new StringBuilder();
		List<TBillProfitExt> list = chnBillDownLoadService.getChnBill(startDate, endDate, chnId, chnName, payType);
		if (list != null && list.size() > 0) {
			sbContent.append("渠道ID,渠道名称,支付类型,费率,商户交易总额,结算金额,开始日期,结束日期\r\n");
			for (TBillProfitExt billProfit : list) {
				if (billProfit != null) {
					String chnname = billProfit.getChnName();
					if(billProfit.getChnName() == null){
						chnname = "";
					}
					sbContent.append("`");
					sbContent.append(billProfit.getToUmid());
					sbContent.append(",`");
					sbContent.append(chnname);
					sbContent.append(",`");
					sbContent.append(billProfit.getPaytypeName());
					sbContent.append(",`");
					sbContent.append(billProfit.getFeeAmt());
					sbContent.append(",`");
					sbContent.append(billProfit.getBaseFee());
					sbContent.append(",`");
					sbContent.append(billProfit.getPayment());
					sbContent.append(",`");
					sbContent.append(billProfit.getStartDate());
					sbContent.append(",`");
					sbContent.append(billProfit.getEndDate());
					sbContent.append("\r\n");
				}
			}
		}
		if(Strings.isNullOrEmpty(chnId)){
			chnId = "";
		}
		String fileName = chnId + "(" + startDate + "-" + endDate + ")" + ".csv";
		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("attachment", fileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(
				sbContent.toString().getBytes(Charset.forName("GBK")), headers, HttpStatus.CREATED);
		return response;
	}
	
	
	
	
	
	
	
	


	*//**
	 * 4.2 合格率检索 请求方式 ：GET 参数 ：partID : 单位ID , Key 软件秘钥 , Datestart 检索条件开始时间
	 * （可为空） , Dateover 检索条件结束时间 （可为空） Machinebrand 品牌 （可为空）,Department 科室（可为空）,
	 * Teststyle 测试项目 （可为空） 条件 ：存在两种 或多种为联合检查模式， 如果全部为空 ，则是全部获取
	 * 
	 * @return 0 不成功 空 , 1 成功 --> 合格率 + 合格数量 + 不合格数量 + 总数
	 * @throws Exception
	 *//*
	@RequestMapping(value = "selectTestHegelv", method = RequestMethod.GET)
	public Map<String, Object> selectTestHegelv(String PartID, String Key, String Datestart, String Dateover,
			String Machinebrand, String Department, String Teststyle) throws Exception {
		log.info("PC接口 :4.2 " + DateUtil.getTime());

		// 字符编码处理
		try {
			if (null != Department) {
				Department = URLDecoder.decode(Department, "GBK");
			}
			if (null != Machinebrand) {
				Machinebrand = URLDecoder.decode(Machinebrand, "GBK");
			}
		} catch (UnsupportedEncodingException e2) {
			log.info("捕获异常：" + DateUtil.getTime() + " " + e2.getMessage());
		}
		// 处理空格
		PartID = PartID.replace(" ", "");
		// 处理PartID 大小写
		try {
			PartID = HelpUtil.TreateHospitalID(PartID);
			// 验证秘钥
			Map<String, Object> paramsMap = new HashMap<String, Object>();
			String city_id = PartID.substring(0, 6).toString();
			String hospital_id = PartID.substring(6).toString();
			paramsMap.put("hospital_id", hospital_id);
			paramsMap.put("t_hospital", Constants.T_HOSPITAL + city_id);
			Hospital hospital = null;
			try {
				hospital = pcService.findHospitalByID(paramsMap);
			} catch (Exception e) {
				log.info("捕获异常：" + DateUtil.getTime() + " " + e.getMessage());
				return MapModel.getMapModel("0", "", "正在建设中，请耐心等待！");
			}
			System.out.println(" 获取的医院信息  ：" + hospital);
			if (null == hospital) {
				return MapModel.getMapModel("0", "", "单位不存在");
			}
			if (!hospital.getHospital_key().equals(Key)) {
				return MapModel.getMapModel("0", "", "秘钥不正确");
			}
			if (null != hospital.getUse_expiry_date()) {
				if (new Date().getTime() > hospital.getUse_expiry_date().getTime()) {
					return MapModel.getMapModel("0", "", "有效期过期");
				}
			}
			// 设置其他参数
			if (null != Datestart && null != Dateover) {
				Datestart = Datestart + " 0:0:0";
				Dateover = Dateover + " 23:59:59";
				paramsMap.put("start_time", DateUtil.fomatDatetime(Datestart));
				paramsMap.put("end_time", DateUtil.fomatDatetime(Dateover));
			}
			paramsMap.put("Machinebrand", Machinebrand);
			paramsMap.put("Department", Department);
			List<String> list = new ArrayList<String>();
			if (null != Teststyle && !"".equals(Teststyle)) {
				if (Teststyle.equals("00s")) { // 灭菌效果
					paramsMap.put("test_tableName", Constants.T_STERILIZATION + city_id);
				} else if (Teststyle.equals("0sd")) { // 灭菌设备
					paramsMap.put("test_tableName", Constants.T_STERILIZATION_DEVICE + city_id);
				} else if (Teststyle.equals("00d")) { // 消毒
					paramsMap.put("test_tableName", Constants.T_DISINFECTED + city_id);
				} else if (Teststyle.equals("0uv")) { // 紫外
					paramsMap.put("test_tableName", Constants.T_UV + city_id);
				} else if (Teststyle.equals("0bd")) { // DB测试
					paramsMap.put("test_tableName", Constants.T_BD_TEST + city_id);
				} else if (Teststyle.equals("atp")) { // ATP测试
					paramsMap.put("test_tableName", Constants.T_ATP_TEST + city_id);
				}
				try {
					list = pcService.findAllRsult(paramsMap);
				} catch (Exception e) {
					log.info("捕获异常：" + DateUtil.getTime() + " " + e.getMessage());
					return MapModel.getMapModel("0", "", "正在建设中，请耐心等待！");
				}
				return getResultForTestHegelv(list);
			}
			
			 * 操作 所有的检测结果
			 
			String testName = null;
			for (int i = 0; i < 6; i++) {
				testName = Constants.type[i];
				if (testName.equals("xd_")) {
					String t_desinfected = Constants.T_DISINFECTED + city_id; // 消毒表
					paramsMap.put("test_tableName", t_desinfected);
				} else if (testName.equals("mj_")) {
					String t_sterilization = Constants.T_STERILIZATION + city_id; // 灭菌
					paramsMap.put("test_tableName", t_sterilization);
				} else if (testName.equals("mjsb_")) {
					String t_sterilization_device = Constants.T_STERILIZATION_DEVICE + city_id; // 灭菌设备
					paramsMap.put("test_tableName", t_sterilization_device);
				} else if (testName.equals("zw_")) {
					String t_uv = Constants.T_UV + city_id; // 紫外效果包
					paramsMap.put("test_tableName", t_uv);
				} else if (testName.equals("atp_")) {
					String t_atp_test = Constants.T_ATP_TEST + city_id; // atp测试包
					paramsMap.put("test_tableName", t_atp_test);
				} else { // db
					String t_db_test = Constants.T_BD_TEST + city_id; // db测试
					paramsMap.put("test_tableName", t_db_test);
				}
				try {
					list.addAll(pcService.findAllRsult(paramsMap));
				} catch (Exception e) {
					log.info("捕获异常：" + DateUtil.getTime() + " " + e.getMessage());
					continue;
				}
			}
			return getResultForTestHegelv(list);
		} catch (Exception e1) {
			log.info("捕获异常：" + DateUtil.getTime() + " " + e1.getMessage());
			return MapModel.getMapModel("0", "", "用户名异常");
		}
	}

	// 获取 合格个数，总数，不合格个数等
	public Map<String, Object> getResultForTestHegelv(List<String> list) {
		int sum = list.size();
		int hege_num = 0;
		int number = 0;
		double hegelv = 0;
		for (String result : list) {
			if (result.equals("1")) {
				hege_num++;
			}
		}
		if (sum == 0) {
			TestHegelv tHegelv = new TestHegelv();
			tHegelv.setHege_num("NaN");
			tHegelv.setSum("NaN");
			tHegelv.setHegelv("NaN");
			tHegelv.setNumber("NaN");
			return MapModel.getMapModel("1", tHegelv, "");
		}
		number = sum - hege_num;
		hegelv = ((double) hege_num / (double) sum);
		System.out.println("  合格率  ： " + hegelv + "  sum :" + sum + " number :" + number + "  hege_num " + hege_num);
		DecimalFormat df = new DecimalFormat("0.00");
		hegelv = Double.valueOf(df.format(hegelv)).doubleValue();
		System.out.println(" 获取的合格率 ：" + df.format(hegelv));
		TestHegelv tHegelv = new TestHegelv();
		tHegelv.setHege_num(String.valueOf(hege_num));
		tHegelv.setSum(String.valueOf(sum));
		tHegelv.setHegelv(String.valueOf(hegelv));
		tHegelv.setNumber(String.valueOf(number));
		return MapModel.getMapModel("1", tHegelv, "");
	}
	
	

	*//**
	 * 5.4  不合格数据原因说明
	 * @param
	 *//*
	@RequestMapping(value = "noPassDataCause", method = RequestMethod.POST)
	public Map<String, Object> noPassDataCause(String PartID, String Key, String Time ,String Reason_style,String Reason_explain , String Dispose_style,String Dispose_Explain,
			String TestID ) {
		
		log.info("PC接口 :5.3 " + DateUtil.getTime());

		// 处理空格
		PartID = PartID.replace(" ", "");
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		String city_id = "";
		String hospital_id = "";
		// 处理PartID 大小写
		try {
			PartID = HelpUtil.TreateHospitalID(PartID);
			// 验证秘钥
			city_id = PartID.substring(0, 6).toString();
			hospital_id = PartID.substring(6).toString();
		} catch (Exception e1) {
			log.info("捕获异常：" + DateUtil.getTime() + " " + e1.getMessage());
			return MapModel.getMapModel("0", "", "用户名异常");
		}
		paramsMap.put("hospital_id", hospital_id);
		paramsMap.put("t_hospital", Constants.T_HOSPITAL + city_id);
		Hospital hospital = null;
		try {
			hospital = pcService.findHospitalByID(paramsMap);
			if (null == hospital) {
				return MapModel.getMapModel("0", "", "单位不存在");
			}
			if (!hospital.getHospital_key().equals(Key)) {
				return MapModel.getMapModel("0", "", "秘钥不正确");
			}
			if (null != hospital.getUse_expiry_date()) {
				if (new Date().getTime() > hospital.getUse_expiry_date().getTime()) {
					return MapModel.getMapModel("1", "", "有效期过期");
				}
			}
			
			// 解析 测试类别
			String dtbType = TestID.substring(0, 3).toString();
			if (dtbType.equals("00s")) { // 灭菌效果
				String table_data = Constants.T_STERILIZATION + city_id ;
				Sterilization sterilization = pcService.getMjData(TestID , table_data ) ;
				sterilization.setTable_data(table_data);
				sterilization.setReason_explain(Reason_explain);
				sterilization.setReason_style(Reason_style);
				sterilization.setDispose_explain(Dispose_Explain);
				sterilization.setDispose_style(Dispose_style);
				
				pcService.updateMjData(sterilization) ;
				
			} else if (dtbType.equals("0sd")) { // 灭菌设备
				
			} else if (dtbType.equals("00d")) { // 消毒
				
			} else if (dtbType.equals("0uv")) { // 紫外
				
			} else if (dtbType.equals("0db")) { // DB测试
				
			} else if (dtbType.equals("atp")) { // ATP测试
				
			} else {
			}
			
			*//*** 修改push 表 不合格数据原因 ***//*
			paramsMap = new HashMap<String, Object>();
			paramsMap.put("spare1", TestID);
			List<Push> list = helpService.findAllPushByScopeAndState(paramsMap) ;
			paramsMap.put("spare2", Reason_explain);
			paramsMap.put("isread", list.get(0).getIsread() );
			paramsMap.put("push_id", list.get(0).getPush_id() );
			helpService.updatePushStateByID(paramsMap) ;
			
		} catch (BusinessException bus) {
			log.info("捕获异常：" + DateUtil.getTime() + " " + bus.getMessage());
			return MapModel.getMapModel("0", "", "业务异常，请联系管理员。");
		} catch (Exception e) {
			log.info("捕获异常：" + DateUtil.getTime() + " " + e.getMessage());
			return MapModel.getMapModel("0", "", "系统异常");
		}

		return MapModel.getMapModel("1", "操作成功", "");
	}
	
	
    public static void main(String[] args) {
		
    	try {
			System.out.println(URLDecoder.decode("\u9ed1\u9f99\u6c5f\u7701", "GBK")) ;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
	}
	

*/





	
	
	
	
	
	
	
	
	

}
